import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../utils/api.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:convert';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  EasyRefreshController _controller;
  int page = 1;
  List<Map> hotGoodsList = [];
  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: AppBar(
          title: Text('八鱼食用油'),
        ),
        body: FutureBuilder(
          future: getHomePageContent(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              print('snapshot${snapshot.data}');
              var data = json.decode(snapshot.data.toString());
              List<Map> swiperDataList =
                  (data['msg']['data']['slides'] as List).cast(); // 顶部轮播组件数
              List<Map> navigatorList =
                  (data['msg']['data']['Category'] as List).cast();
              String adPicture = (data['msg']['data']['banner']).toString();
              String leaderImage =
                  (data['msg']['data']['shopInfo']['leaderImage']).toString();
              String leaderPhone =
                  (data['msg']['data']['shopInfo']['leaderPhone']).toString();
              List<Map> recommendList =
                  (data['msg']['data']['recommend'] as List).cast();
              Map floorData = data['msg']['data']['floorData'];
              // print('返回$floorData');
              return EasyRefresh(
                enableControlFinishRefresh: false,
                firstRefresh:true,
                bottomBouncing:true,
                controller: _controller,
                header: null,
                footer: ClassicalFooter(
                  loadedText:'加载完成',
                  loadingText: '加载中',
                  noMoreText:'已经到达底部',
                 bgColor: Colors.white,
                 textColor: Colors.pink,
                 showInfo: false,
                ),
                child: ListView(
                  children: <Widget>[
                    SwiperDiy(swiperDataList: swiperDataList), //页面顶部轮播组件
                    TopNavigator(
                      navigatorList: navigatorList,
                    ),
                    AdBanner(
                      adPictuer: adPicture,
                    ),
                    LeaderPhone(
                      leaderImage: leaderImage,
                      leaderPhone: leaderPhone,
                    ),
                    Recommend(
                      recommendList: recommendList,
                    ),
                    Floor(
                      floorData: floorData,
                    ),
                    _hotGoods(),
                  ],
                ),
                onLoad: () async {
                  await Future.delayed(Duration(seconds: 2), () {
                    _getHotGoods();
                  });
                  _controller.finishLoad(success:true,noMore: page >= 3);
                  _controller.resetLoadState();
                },
              );
            } else {
              return Center(
                child: Text('加载中'),
              );
            }
          },
        ));
  }

  void _getHotGoods() {
    pageBelowConten(page).then((value) {
      var data = json.decode(value.toString());
      List<Map> newGoodsList = (data['msg']['data'] as List).cast();
      setState(() {
        hotGoodsList.addAll(newGoodsList);
        page++;
        print('currentPage$page');
      });
    });
  }

  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 10.0),
    alignment: Alignment.center,
    color: Colors.transparent,
    child: Text(
      '火爆专区',
      style: TextStyle(color: Colors.red),
    ),
  );

  Widget _wrapList() {
    if (hotGoodsList.length != 0) {
      List<Widget> listWiget = hotGoodsList
          .map(
            (e) => InkWell(
              onTap: () {},
              child: Container(
                width: 372.w,
                color: Colors.white,
                padding: EdgeInsets.all(5.0),
                margin: EdgeInsets.only(bottom: 3.0),
                child: Column(
                  children: <Widget>[
                    Image.network(
                      e['image'],
                      width: 370.w,
                    ),
                    Text(
                      e['name'],
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Colors.pink, fontSize: 26.sp),
                    ),
                    Row(
                      children: <Widget>[
                        Text('￥${e['mallPrice']}'),
                        Text(
                          '￥${e['price']}',
                          style: TextStyle(
                              color: Colors.black26,
                              decoration: TextDecoration.lineThrough),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          )
          .toList();
      return Wrap(
        spacing: 2,
        children: listWiget,
      );
    } else {
      return Text('');
    }
  }

  Widget _hotGoods() {
    return Column(
      children: <Widget>[hotTitle, _wrapList()],
    );
  }
}

// 首页轮播组件编写
class SwiperDiy extends StatelessWidget {
  final List swiperDataList;
  SwiperDiy({Key key, this.swiperDataList}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 300.w,
      width: 750.h,
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return Image.network("${swiperDataList[index]['image']}",
              fit: BoxFit.cover);
          // fit: BoxFit.scaleDown);
        },
        itemCount: swiperDataList.length,
        pagination: new SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}

// 首页顶部导航
class TopNavigator extends StatelessWidget {
  final List navigatorList;
  TopNavigator({this.navigatorList});
  Widget _gridViewItemUI(BuildContext context, item) {
    return InkWell(
      onTap: () {
        print('点击了导航');
      },
      child: Column(
        children: <Widget>[
          Image.network(
            item['image'],
            width: 95.w,
          ),
          Container(
            child: Text(
              item['mallCategoryName'],
            ),
            margin: EdgeInsets.fromLTRB(0, 5.0, 0, 0),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 160.h,
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 4,
        padding: EdgeInsets.all(5.0),
        children: navigatorList.map((e) {
          return _gridViewItemUI(context, e);
        }).toList(),
      ),
    );
  }
}

// 首页banner
class AdBanner extends StatelessWidget {
  final String adPictuer;
  AdBanner({this.adPictuer});
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(
        adPictuer,
        filterQuality: FilterQuality.high,
        fit: BoxFit.cover,
        width: 750.w,
      ),
      height: 100.h,
    );
  }
}

// 拨打店长电话
class LeaderPhone extends StatelessWidget {
  final String leaderImage, leaderPhone;
  LeaderPhone({this.leaderImage, this.leaderPhone});
  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: () {
          _launchUrl();
        },
        child: Image.network(
          leaderImage,
          fit: BoxFit.fill,
          width: 750.w,
        ),
      ),
      height: 200.h,
    );
  }

  void _launchUrl() async {
    String url = 'tel:' + leaderPhone;
    print(url);
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'url ERROR';
    }
  }
}

// 商品推荐
class Recommend extends StatelessWidget {
  final List recommendList;
  Recommend({this.recommendList});
  // 推荐商品标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 0.5, color: Colors.black12)),
      ),
      child: Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  // 商品单独方法
  Widget _item(index) {
    return InkWell(
      onTap: () {},
      child: Container(
        height: 330.h,
        width: 250.w,
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            left: BorderSide(width: 0.5, color: Colors.black12),
          ),
        ),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text('\$${recommendList[index]['mallPrice']}'),
            Text('\$${recommendList[index]['Price']}',
                style: TextStyle(
                    decoration: TextDecoration.lineThrough,
                    color: Colors.green)),
          ],
        ),
      ),
    );
  }

  // 横向列表
  Widget _recommendList() {
    return Container(
        height: 330.h,
        margin: EdgeInsets.only(top: 10.0),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: recommendList.length,
          itemBuilder: (context, index) => _item(index),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 400.h,
      margin: EdgeInsets.only(top: 10.0),
      child: Column(
        children: <Widget>[_titleWidget(), _recommendList()],
      ),
    );
  }
}

// 楼层
class Floor extends StatelessWidget {
  final Map floorData;
  Floor({this.floorData});

  // 顶层图片
  Widget _top(String topImage, width) {
    return Container(
      width: width,
      child: InkWell(
        onTap: () {},
        child: Image.network(topImage),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          this._top(floorData['top'], 750.w),
          Row(
            children: <Widget>[
              this._top(floorData['middle']['left'], 375.w),
              Column(
                children: <Widget>[
                  this._top(floorData['middle']['right']['top'], 375.w),
                  this._top(floorData['middle']['right']['bottom'], 375.w),
                ],
              ),
            ],
          ),
          Row(
            children: <Widget>[
              this._top(floorData['bottom']['left'], 375.w),
              this._top(floorData['bottom']['right'], 375.w),
            ],
          ),
        ],
      ),
    );
  }
}
